package com.smp.bitmapgridtest;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.smp.bitmapgridtest.BitmapWorkerTask.OnBitmapWorkerListener;

public class TestMainActivity extends Activity {

	private String STORAGE_IMAGE_FILE_PATH = "/storage/sdcard0/temp";
	private ArrayList<File> mImgFileList = new ArrayList<File>();
	private BitmapCacheHelper mBitmapCacheHelper;
	
	private Bitmap mPlaceHolderBitmap = null;
	private GridView mgvBitmapGrid = null;
	private ImageListAdapter mImageListAdapter = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_main_activity_layout);
		
		mPlaceHolderBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
		
		mBitmapCacheHelper = new BitmapCacheHelper(getApplicationContext());
		
		mgvBitmapGrid = (GridView) findViewById(R.id.gvBitmapGrid);
		mImageListAdapter = new ImageListAdapter(this, 0, mImgFileList);
		mgvBitmapGrid.setAdapter(mImageListAdapter);

		reloadImageFiles();
	}
	
	@Override
	protected void onDestroy() {
		if(mPlaceHolderBitmap != null) {
			mPlaceHolderBitmap.recycle();
			mPlaceHolderBitmap = null;
		}
		
		super.onDestroy();
	}

	private void loadBitmap(ImageView aTargetView, File aImageFile) {
		
		if(cancelPotentialWork(aTargetView, aImageFile)) {

			final Bitmap bitmap = mBitmapCacheHelper.getBitmapFromCache(aImageFile.getAbsolutePath());
			if(bitmap != null) {
				aTargetView.setImageBitmap(bitmap);
			}
			else {
				final BitmapWorkerTask task = new BitmapWorkerTask(aTargetView, aImageFile);
				task.setOnBitmapWorkerListener(new OnBitmapWorkerListener() {
					@Override
					public void onBitmapLoaded(String aFilePath, Bitmap aBitmap) {
						mBitmapCacheHelper.cacheBitmap(aFilePath, aBitmap);
					}
				});
				final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);
				aTargetView.setImageDrawable(asyncDrawable);
				task.execute();
			}
		}
	}
	
	private boolean cancelPotentialWork(ImageView aTargetView, File aImageFile) {
		final BitmapWorkerTask bitmapWorkerTask = BitmapWorkerHelper.getBitmapWorkerTask(aTargetView);
		if(bitmapWorkerTask != null) {
			final File imageFile = bitmapWorkerTask.getTargetFile();
			
			if(aImageFile.getAbsolutePath().equalsIgnoreCase(imageFile.getAbsolutePath()) == false) {
				//cancel previous task
				bitmapWorkerTask.cancel(true);
			}
			else {
				//the same work is already in progress
				return false;
			}
		}
		//no task associated with the imageview, or an existing task was canceled
		return true;
	}
	
	private class ImageListAdapter extends ArrayAdapter<File> {

		private Context mContext;
		
		public ImageListAdapter(Context aContext, int aTextViewResourceId, List<File> aImageList) {
			super(aContext, aTextViewResourceId, aImageList);
			
			mContext = aContext;
		}

		@Override
		public View getView(int aPosition, View aConvertView, ViewGroup aParent) {
			View localView = aConvertView;
			GridImageHolder holder;
			File imageFile = getItem(aPosition);
			
			if(localView == null) {
				localView =  View.inflate(mContext, R.layout.test_bitmap_view_layout, null);
				holder = new GridImageHolder(localView);
			}
			else {
				holder = (GridImageHolder)localView.getTag();
			}
			localView.setTag(holder);
			
			loadBitmap(holder.aImageView, imageFile);
			
			return localView;
		}
		
	}
	
	private static class GridImageHolder {
		private ImageView aImageView;
		
		public GridImageHolder(View aContainerView) {
			aImageView = (ImageView) aContainerView.findViewById(R.id.ivBitmap);
		}
	}
	
	private void reloadImageFiles() {
		final File targetDir = new File(STORAGE_IMAGE_FILE_PATH);
		
		if(targetDir.isDirectory() == false) {
			return;
		}
		
		(new AsyncTask<Void, Void, ArrayList<File>>() {

			@Override
			protected ArrayList<File> doInBackground(Void... params) {
				ArrayList<File> resultFiles = new ArrayList<File>();
				
				File[] arrFiles = targetDir.listFiles(new ImageFileFilter());
				if(arrFiles == null){
					return resultFiles;
				}
				
				for(File file : arrFiles) {
					resultFiles.add(file);
				}
				return resultFiles;
			}

			@Override
			protected void onPostExecute(ArrayList<File> aResultFileList) {
				mImgFileList.clear();
				mImgFileList.addAll(aResultFileList);
				
				mImageListAdapter.notifyDataSetChanged();
			}
			
		}).execute();
		
	}
	
	static class ImageFileFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String filename) {
			String lowerFileName = filename.toLowerCase();
			if(lowerFileName.endsWith(".png")) {
				return true;
			}
			
			return false;
		}
		
	}
}
